<template>
    <div class="page-wrap page-wrap-ql" v-loading="loading" :loading-tip="loadingObj.tip">
        <div class="page-cont" v-if="detail.id">
            <a-page-header @back="handleBack">
                <template #title> 【{{ detail.systemName }}】{{ detail.reportName }} </template>
                <flexbox justify="space-between" align="flex-start">
                    <a-form layout="inline" style="flex: 1">
                        <a-row>
                            <a-col :span="24">
                                <a-row :gutter="6">
                                    <a-col>
                                        <a-form-item label="项目经理/负责人">
                                            {{ detail.requireManager }}
                                        </a-form-item>
                                    </a-col>
                                    <a-col>
                                        <a-form-item label="产品经理">
                                            {{ detail.productManager }}
                                        </a-form-item>
                                    </a-col>
                                    <a-col :span="detail.jiraSyncTmplDTO ? 4 : 5">
                                        <a-form-item label="系统类型">
                                            {{ $filters.valToNameFilter('systemType', detail.systemType) }}
                                        </a-form-item>
                                    </a-col>
                                    <a-col :span="detail.jiraSyncTmplDTO ? 3 : 4">
                                        <a-form-item label="来源">
                                            {{ detail.dataSource }}
                                        </a-form-item>
                                    </a-col>
                                    <a-col :span="detail.jiraSyncTmplDTO ? 5 : 3">
                                        <a-form-item label="对接JIRA">
                                            <span>{{ detail.jiraSyncTmplDTO ? detail.jiraSyncTmplDTO?.projectName : '' }}</span>
                                        </a-form-item>
                                    </a-col>
                                </a-row>
                            </a-col>
                        </a-row>
                    </a-form>
                    <flexbox v-if="detail.dataSource === '外部'">
                        <a-button type="primary" :disabled="loading || disabled" class="margin-l-8" @click="getIssuseList"> 同步刷新 </a-button>
                        <a-tooltip>
                            <template #title>
                                <span
                                    v-html="
                                        `如JIRA信息未更新导致报告数据不准确，可更新JIRA数据后点击【同步刷新】按钮更新报告内容。<br />如有删除的信息请等待数分钟后可自动同步更新。`
                                    "
                                />
                            </template>
                            <QuestionCircleOutlined class="margin-l-8" />
                        </a-tooltip>
                    </flexbox>
                </flexbox>
            </a-page-header>
            <div style="padding: 16px 40px 0 40px" v-if="!disabled && detail.dataSource === '外部'">
                <a-checkbox :checked="isNoData" @change="handleChange">本周期内没有需求数据</a-checkbox>
            </div>
            <div style="padding: 16px 40px 0 40px; color: #d46b08" v-if="disabled && isNoData">本周期内没有需求变更</div>
            <DetailB
                ref="detailARef"
                :hasAuth="hasAuth"
                :detail="detail"
                :isNoData="isNoData"
                @success="getDetailData"
                v-if="detail.dataSource === '外部' && detail.pmpProductDetailDTO.projectKey"
            />
            <DetailA ref="detailARef" :hasAuth="hasAuth" :detail="detail" :isNoData="isNoData" v-else />
            <a-form layout="inline" ref="ruleFormRef" :model="form" :rules="rules" v-if="+detail.stage >= 3 || detail.status === '已拒绝'">
                <a-row>
                    <a-col :span="16">
                        <a-form-item label="审核意见" name="auditOpinion">
                            <div style="width: 100%">
                                <a-textarea
                                    v-model:value="form.auditOpinion"
                                    showCount
                                    :maxlength="500"
                                    auto-size
                                    v-if="+detail.stage >= 3 && hasAuth"
                                />
                                <span style="white-space: pre-wrap" v-html="form.auditOpinion" v-else />
                            </div>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>

            <flexbox style="padding: 16px 48px" justify="flex-end" v-if="hasAuth">
                <a-button @click="handleSave" v-if="detail.stage === '2' && !(detail.dataSource === '外部' && detail.pmpProductDetailDTO.projectKey)"
                    >保存</a-button
                >
                <a-button @click="handleSubmit('否')" v-if="+detail.stage >= 3">驳回</a-button>
                <a-button class="margin-l-8" type="primary" @click="handleSubmit('是')">提交</a-button>
                <a-button class="margin-l-8" type="primary" @click="handleOpenZhuanban" v-if="detail.stage === '2'">转办</a-button>
            </flexbox>
            <history-record :detail="detail" :historyList="historyList" />
            <ZhuanbanModal ref="ZhuanbanModalRef" @success="handleZhuanban" />
        </div>
    </div>
</template>

<script lang="ts">
import api from '@/api';
import store from '@/store';
import { useMessage } from '@/hooks/common/useMessage';
import DetailA from './DetailA/index.vue';
import DetailB from './DetailB/index.vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue/es';
import { HistoryRecord, ZhuanbanModal } from './DetailA/components/index';
import { useRouterApi } from '@/hooks/common/useRouterApi';
import { useSyncRequest } from './hooks/useJiraSyncRequest';
import { QuestionCircleOutlined } from '@ant-design/icons-vue';
import { defineComponent, ref, unref, reactive, toRefs, computed, nextTick } from 'vue';
export default defineComponent({
    components: {
        HistoryRecord,
        ZhuanbanModal,
        DetailA,
        DetailB,
        QuestionCircleOutlined
    },
    setup(_, { emit }) {
        const router = useRouter();
        const detailARef = ref<any>();
        const ruleFormRef = ref<any>();
        const ZhuanbanModalRef = ref<any>();
        const { handleBack, route } = useRouterApi({
            backQuery: {
                path: '/energyManage/analysisReport'
            }
        });
        const loading = ref<boolean>(false);
        const state = reactive<any>({
            detail: {},
            requireInfos: [],
            releaseVersion: [],
            processVersion: [],
            unOnlineVersion: [],
            form: {
                auditOpinion: '',
                pass: '是'
            },
            historyList: [],
            hasAuth: false,
            isNoData: false
        });
        const setLoading = (isLoading: boolean) => {
            loading.value = isLoading;
        };
        const { loadingObj, syncDataFromJira } = useSyncRequest(loading, setLoading, emit);

        const rules = computed(() => {
            const rules = {
                auditOpinion: state.form.pass === '否' ? [{ required: true, message: '审核意见不能为空', trigger: 'change' }] : []
            };
            return rules;
        });
        const disabled = computed(() => {
            return +state.detail.stage > 2 || !state.hasAuth;
        });
        const handleChange = async (val) => {
            if (val.target.checked) {
                const { createConfirm } = useMessage();
                createConfirm({
                    title: '该操作会清空所有已填写数据？',
                    iconType: 'danger',
                    onOk: async () => {
                        state.isNoData = val.target.checked;
                        const query = {
                            id: route.query.id,
                            isNoData: state.isNoData ? 1 : 0
                        };
                        const { success } = await api.requireReportModel.saveSystemReport(query);
                        if (success) {
                            getDetailData();
                        }
                    },
                    onCancel: () => {
                        state.isNoData = false;
                    }
                });
            } else {
                state.isNoData = val.target.checked;
                const query = {
                    id: route.query.id,
                    isNoData: state.isNoData ? 1 : 0
                };
                const { success } = await api.requireReportModel.saveSystemReport(query);
                if (success) {
                    state.detail = {
                        ...state.detail,
                        isNoData: state.isNoData ? 1 : 0
                    };
                }
                state.isNoData = val.target.checked;
            }
        };
        const handleSave = async (showMsg = true) => {
            let res = true;
            if (state.form.pass !== '转办' && !state.isNoData) {
                const arr = await unref(detailARef).validate();
                res = arr.every((item) => item);
            }
            if (res) {
                if (showMsg) {
                    loading.value = true;
                }
                const query = unref(detailARef).getList();
                const { success, errorMsg } = await api.requireReportModel.save(query);
                if (success) {
                    getDetailData();
                    showMsg && message.success('保存成功');
                } else {
                    message.error(errorMsg);
                }
                if (showMsg) {
                    loading.value = false;
                }
                return success;
            } else {
                return false;
            }
        };
        const handleValidate = () => {
            return new Promise((res) => {
                unref(ruleFormRef)
                    .validate()
                    .then(
                        () => {
                            res(true);
                        },
                        () => {
                            res(false);
                        }
                    );
            });
        };
        const handleOpenZhuanban = () => {
            unref(ZhuanbanModalRef).open();
        };
        const handleZhuanban = (query) => {
            handleSubmit('转办', query);
        };
        const handleSubmit = (pass, params = {}) => {
            let res: any = true;
            state.form.pass = pass;
            loading.value = true;
            nextTick(async () => {
                if (pass === '否') {
                    res = await handleValidate();
                    if (!res) {
                        loading.value = false;
                        return;
                    }
                } else {
                    unref(ruleFormRef) && unref(ruleFormRef).clearValidate();
                }
                handleSave(false).then(async (res) => {
                    if (res) {
                        const query = {
                            ...state.detail,
                            auditOpinion: state.detail.stage === '2' ? '' : state.form.auditOpinion,
                            pass,
                            ...params
                        };
                        const { success, errorMsg } = await api.requireReportModel.auditProcess(query);
                        loading.value = false;
                        if (success) {
                            router.push({
                                path: '/workbench'
                            });
                        } else {
                            message.error(errorMsg);
                        }
                    } else {
                        loading.value = false;
                    }
                });
            });
        };
        const getHistoryList = async (instanceId) => {
            const query = {
                instanceId,
                type: 'systemReport'
            };
            const { success, moule, errorMsg } = await api.historyModel.historyOperationByInstanceId(query);
            if (success) {
                if (moule && moule.length) {
                    state.historyList = [...moule];
                    // 审批节点操作人不是当前用户的无需显示
                    const target = state.historyList[state.historyList.length - 1];
                    if (target) {
                        state.hasAuth = target.assignee.indexOf(store.getters.userInfo.employeeDTO.empId) >= 0;
                    }
                }
            } else {
                message.error(errorMsg);
            }
        };
        const getDetailData = async () => {
            loading.value = true;
            const query = {
                id: route.query.id
            };
            const { success, moule, errorMsg } = await api.requireReportModel.findById(query);
            if (success) {
                state.detail = { ...moule };
                state.form.auditOpinion = '';
                if (moule.isNoData !== null) {
                    state.isNoData = moule.isNoData === '1' ? true : false;
                }
                getHistoryList(moule.instanceId);
            } else {
                message.error(errorMsg);
            }
            loading.value = false;
        };
        getDetailData();

        // 异步获取
        const getIssuseList = () => {
            const fn = () => {
                getDetailData();
            };
            syncDataFromJira(
                api.jiraModel.syncIssueFromJira,
                {
                    systemId: state.detail.systemId
                },
                fn
            );
        };
        return {
            ...toRefs(state),
            handleBack,
            getDetailData,
            handleSave,
            handleSubmit,
            ruleFormRef,
            rules,
            handleOpenZhuanban,
            handleZhuanban,
            ZhuanbanModalRef,
            detailARef,
            handleChange,
            disabled,
            loading,
            getIssuseList,
            loadingObj
        };
    }
});
</script>
<style scoped lang="less">
.page-wrap {
    height: 100%;
    position: relative;
    .page-cont {
        background: #fff;
        .btn-group {
            margin: 24px 0;
            button + button {
                margin-left: 8px;
            }
        }
        .tip-cont {
            color: #d46b08;
            background: #fff7e6;
            border-color: #ffd591;
            padding: 6px 12px;
            font-size: 14px;
        }
    }
}
// 去掉表头颜色
::v-deep(.ant-table-thead) > tr > th {
    background: #eaf5fe !important;
    font-weight: 400;
    color: @primary-color;
}
::v-deep(.ant-divider) {
    border-top: 2px solid #eaf5fe;
}
</style>
